'use strict';
/**
 * 此文件解决 vue-tsc 无法在 nodejs12+ 下运行的问题
 */
const fs = require('fs');
const vueTscPath =
  (require.resolve('vite') || process.cwd() + 'node_modules/vite/dist/node/index.js').replace(/\\/g, '/').split('/vite/dist/node/')[0] +
  '/vue-tsc/bin/vue-tsc.js';
if (parseInt(process.version.replace('v', '')) < 14 && fs.existsSync(vueTscPath)) {
  let code = fs.readFileSync(vueTscPath, 'utf8');
  if (!(code.indexOf('##########################################################') != -1)) {
    const ecode = `
//##########################################################
// 以下代码放置进 node_modules/vue-tsc/bin/vue-tsc.js 文件
//==========================================================
const NodeVersion = process.version.replace('v', '');
parseInt(NodeVersion) < 14 && require('@babel/register')({
    presets: ['@vue/cli-plugin-babel/preset'],
    ignore: [
    function (filename) {
        if (!/\.(c|m)?js$/.test(filename) && !filename.indexOf('vue-tsc')) {
          return true;
        }
        if(filename.indexOf('tsc.js') != -1 || filename.indexOf('tsserverlibrary.js') != -1){
          return true;
        }
        const source = fs.readFileSync(filename, 'utf8');
        if (source.indexOf('?.') != -1 || source.indexOf('??') != -1) {
          return false;
        }
        return true;
    }
    ],
    cache: true
});
//##########################################################\r\n\r\n`;
    code = code.replace('const readFileSync', ecode + 'const readFileSync');
    fs.writeFileSync(vueTscPath, code);
  }
}
